package com.example.demo.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Service
public class TokenService {

    private static final Logger logger = LoggerFactory.getLogger(TokenService.class);

    @Value("${openapi.appid}")
    private String appid;

    @Value("${openapi.password}")
    private String password;

    // 默认租户ID，您可以根据需要修改或从配置中获取
    @Value("${openapi.tenantId:0}")
    private Long tenantId;

    private final RestTemplate restTemplate;

    public TokenService(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    public Map<String, Object> getToken() {
        String url = "http://47.113.106.7:8089/openapi/v1/getToken";

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);

        String timestamp = String.valueOf(System.currentTimeMillis());
        String identifier = generateIdentifier(appid, password, timestamp);

        // 添加日志输出
        logger.info("生成的 identifier: {}", identifier);
        logger.info("使用的参数 - appid: {}, timestamp: {}", appid, timestamp);

        // 创建TokenVerifyBo对象
        Map<String, Object> tokenData = new HashMap<>();
        tokenData.put("appid", appid);
        tokenData.put("password", password);
        tokenData.put("timestamp", timestamp);
        tokenData.put("identifier", identifier);
        tokenData.put("tenantId", tenantId); // 添加租户ID字段

        // 创建完整请求对象
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("data", tokenData);
        String requestId = UUID.randomUUID().toString().replace("-", "");
        requestBody.put("requestId", requestId);

        logger.info("完整请求内容: {}", requestBody);

        HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(requestBody, headers);

        Map<String, Object> response = restTemplate.postForObject(url, requestEntity, Map.class);
        logger.info("API 响应: {}", response);

        return response;
    }

    private String generateIdentifier(String appid, String password, String timestamp) {
        String combined = appid + password + timestamp;
        logger.info("计算 identifier 的组合字符串: {}", combined);
        String md5Result = org.springframework.util.DigestUtils.md5DigestAsHex(combined.getBytes());
        logger.info("计算得出的 MD5 identifier: {}", md5Result);
        return md5Result;
    }
}